package com.java.basis.reference;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author wangning
 * @date 2023/5/18 16:13
 */
public class WeakHashMapDemo {
    public static void main(String[] args) {
        myHashMap();
        System.out.println("=========================");
        myWeakHashMap();
    }

    public static void myHashMap() {
        Map<Integer, String> map = new HashMap<>();
        Integer key = new Integer(1);
        String str = "hash map";
        map.put(key, str);
        System.out.println(map);
        key = null;
        System.out.println(map);

        System.gc();
        System.out.println(map);

    }

    public static void myWeakHashMap() {
        WeakHashMap<Integer, String> map = new WeakHashMap<>();
        Integer key = new Integer(1);
        String str = "weak hash map";
        map.put(key, str);
        System.out.println(map);
        key = null;//当key置空的时候，WeakHashMap在垃圾回收的时候会被回收
        System.out.println(map);

        System.gc();
        System.out.println(map);
    }


}
